import fs from 'node:fs';
import path from 'node:path';



let exists = (file) => {
	try {
		fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
		return true;
	}
	catch (err) {
		return false;
	}
}

let mkdir = (dir) => {
	if( !exists(dir) ){
		fs.mkdirSync(dir);
	}
}

let copy = (src, tar) => {
	if( Array.isArray(src) ){
		return src.forEach(s => copy(s, tar));
	}
	if( Array.isArray(tar) ){
		return tar.forEach(t => copy(src, t));
	}
	if( typeof(src) != 'string' ){
		throw new Error('illegal src argument.' + src);
	}
	if( typeof(tar) != 'string' ){
		throw new Error('illegal tar argument.' + tar);
	}

	if( !exists(src) ){
		throw new Error("can't found src." + src);
	}

	let target = path.extname(tar) ? tar :  path.resolve(tar, path.basename(src));

	mkdir(path.dirname(target));

	let stat = fs.statSync(src);
	if( stat.isFile() ){
		fs.copyFileSync(src, target);
	}
	else if( stat.isDirectory() ){
		fs.readdirSync(src).forEach(name => {
			copy(path.resolve(src, name), target);
		});
	}
	else {
		throw new Error('unsupport src.' + src);
	}
}


import process from 'node:process';
import {spawn} from 'node:child_process';

let pre = () => {
	return new Promise((resolve, reject) => {
		if( !exists('dist/markup.js') || !exists('dist/markup.umd.cjs') ){
			let cmd = spawn('npm', ['run', 'build'], { shell : process.platform == 'win32', stdio : 'inherit' });
				cmd.on('close', (code) => resolve(code));
				cmd.on('error', (err) => reject(err));
		}
		else {
			resolve(0);
		}
	});
}


let fileOptions = {encoding:'utf-8'};

let build = () => {

	copy(['package.json', 'README.md', 'dist/markup.js', 'dist/markup.umd.cjs'], 'dist/npm');

	let file = 'dist/npm/package.json';
	let content = fs.readFileSync(file, fileOptions);
	let pkg = JSON.parse(content);
	delete pkg.main;
	delete pkg.scripts;
	pkg.exports = {
		"import": "./markup.js",
		"require": "./markup.umd.cjs" 
	};
	pkg.version = (vers => vers.map((n, i) => parseInt(n) + (i == vers.length - 1 ? 1 : 0)).join('.'))(pkg.version.split('.'));

	fs.writeFileSync(file, JSON.stringify(pkg, null, 4), fileOptions);

	return Object.assign(JSON.parse(content), {version: pkg.version});
}

let publish = () => {
	return new Promise((resolve, reject) => {
		let cmd = spawn('npm', ['publish'], { shell : process.platform == 'win32', stdio : 'inherit', cwd : 'dist/npm' });
			cmd.on('close', (code) => resolve(code));
			cmd.on('error', (err) => reject(err));
	});
}

pre().then(code => {
	if( code === 0 ){
		let pkg = build();
		publish().then(code => {
			if( code === 0 ){
				fs.writeFileSync('package.json', JSON.stringify(pkg, null, 4), fileOptions);
				console.info(pkg);
				console.info('success');
			}
		});
	}
});
